package com.api.tournament.controller;

import com.api.common.EmailUtil;
import com.api.core.annotation.PowerEnable;
import com.api.core.config.AuthUser;
import com.api.core.controller.Ctrl;
import com.api.core.response.Result;
import com.api.core.response.ResultGenerator;
import com.api.tournament.model.Round;
import com.api.tournament.model.Tournament;
import com.api.tournament.model.TournamentReward;
import com.api.tournament.model.TournamentRewardUser;
import com.api.tournament.service.*;
import com.api.tournament.vo.FreeRankVo;
import com.api.tournament.vo.SwapRoundVo;
import com.api.tournament.vo.TournamentAdd;
import com.api.tournament.queue.TournamentStartDelayedMessage;
import com.api.tournament.queue.TournamentStartDelayedService;
import com.api.tournament.vo.TournamentTeamUserVo;
import com.api.user.model.UserInfo;
import com.api.user.service.UserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;


/**
* Created by wanghuiwen on 2021/03/23.
*/
@PowerEnable(name = "赛事",url = "/tournament")
@Api(value = "赛事", tags = {"赛事"})
@RestController
@RequestMapping("/tournament")
public class TournamentController extends Ctrl{
    @Resource
    private TournamentService tournamentService;
    @Resource
    private RoundService roundService;
    @Resource
    private TournamentTeamService tournamentTeamService;
    @Resource
    private RoundLogService roundLogService;
    @Resource
    private UserInfoService userInfoService;
    @Resource
    private TournamentRewardService tournamentRewardService;
    @Resource
    private TournamentStartDelayedService tournamentStartDelayedService;

    @ApiOperation(value = "赛事添加", tags = {"赛事"}, notes = "赛事添加")
    @PostMapping(value="/add",name="赛事添加")
    public Result add(@RequestBody TournamentAdd tournamentAdd, Authentication authentication) {
        return tournamentService.add(tournamentAdd,getAuthUser(authentication));
    }

    @ApiOperation(value = "赛事详细信息", tags = {"赛事"}, notes = "赛事详细信息")
    @PostMapping(value="/detail",name="赛事详细信息")
    public Result detail(@RequestParam Long tournamentId,@RequestParam(defaultValue = "true") Boolean isCheckIn) {
        return tournamentService.detail(tournamentId,isCheckIn);
    }

    @ApiOperation(value = "赛事奖品确认", tags = {"赛事"}, notes = "赛事奖品确认")
    @PostMapping(value="/reward/confirm",name="赛事奖品确认")
    public Result rewardConfirm(Long rewardId,Boolean confirm ) {

        return tournamentService.rewardConfirm(rewardId,confirm);
    }

    @ApiOperation(value = "赛事审核", tags = {"赛事"}, notes = "赛事审核")
    @PostMapping(value="/review",name="赛事审核")
    public Result review(Long tournamentId,Integer examine,String reason,Authentication authentication) {
        AuthUser authUser = getAuthUser(authentication);
        return tournamentService.review(tournamentId,examine,reason,authUser);
    }

    @ApiOperation(value = "赛事报名", tags = {"赛事"}, notes = "赛事报名")
    @PostMapping(value="/signup",name="赛事报名")
    public Result signup(Long tournamentId,Long teamId,String userIds,Authentication authentication) {
        String[] userId = new String[0];
        if(userIds!=null){
            userId  = userIds.split(",");
        }
        AuthUser user = getAuthUser(authentication);
        Result result = tournamentService.signup(tournamentId,teamId,user,userId);
        if(result.getCode() == 200){
            for (String s : userId) {
                UserInfo info = userInfoService.findById(s);
                Tournament tournament = tournamentService.findById(tournamentId);
                if(info!=null) EmailUtil.gmailSender(info.getEmail(),"Congratulations, your registration for the  "+tournament.getTournamentName()+" has been completed.  Please make sure all details submitted are accurate and true and don't forget to 'Check-in' once everything is confirmed !!",null);

            }
        }
        return result;
    }

    @ApiOperation(value = "赛事签到", tags = {"赛事"}, notes = "赛事签到")
    @PostMapping(value="/checkin",name="赛事报名")
    public Result checkin(Long tournamentId,Authentication authentication) {
        AuthUser user = getAuthUser(authentication);
        Result result =  tournamentService.checkin(tournamentId,user.getId());
        if(result.getCode() == 200){
            UserInfo userInfo = userInfoService.findById(getAuthUser(authentication).getId());
            if(userInfo.getEmail()!=null) EmailUtil.gmailSender(userInfo.getEmail(), "Thank you for checking-in, we have acknowledged your check-in, all the best to you !",null);
        }
        return result;
    }

    @ApiOperation(value = "管理员/主持人赛事签到", tags = {"赛事"}, notes = "管理员")
    @PostMapping(value="/admin/checkin",name="管理员")
    public Result adminCheckin(Long tournamentId,Long userId) {
        return tournamentService.checkin(tournamentId,userId);
    }

    @ApiOperation(value = "确认赛事报名完成", tags = {"赛事"}, notes = "确认赛事报名完成")
    @PostMapping(value="/end/registration",name="确认赛事报名完成")
    public Result endRegistration(Long tournamentId) {
        return tournamentService.endRegistration(tournamentId);
    }

    @ApiOperation(value = "赛事列表信息", tags = {"赛事"}, notes = "赛事列表信息")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "search", value = "查询条件json", dataType = "String", paramType = "query"),
        @ApiImplicitParam(name = "order", value = "排序json", dataType = "String", paramType = "query"),
        @ApiImplicitParam(name = "page", value = "页码", dataType = "String", paramType = "query"),
        @ApiImplicitParam(name = "size", value = "每页显示的条数", dataType = "String", paramType = "query", defaultValue = "10")
    })
    @PostMapping(value = "/list", name = "赛事列表信息")
    public Result list(
                        @RequestParam(required = false) Integer state,
                        @RequestParam(required = false) Integer tournamentType,
                        @RequestParam(required = false) String tournamentName,
                        @RequestParam(required = false) String tournamentCategory,
                        @RequestParam(required = false) Boolean hot,
                        @RequestParam(required = false) Long gameId,
                        @RequestParam(required = false) Long createUser,
                        @RequestParam(required = false) Integer format,
                       @RequestParam(defaultValue = "{}") String order,
                       @RequestParam(defaultValue = "0") Integer page,
                       @RequestParam(defaultValue = "10") Integer size,
                        Authentication authentication) {
        AuthUser user = getAuthUser(authentication);
        return tournamentService.list(state,tournamentName,tournamentType,hot,gameId,tournamentCategory,createUser,format, order, page, size,user);
    }

    @PostMapping(value = "user/list", name = "赛事列表信息")
    public Result userList(
            @RequestParam(required = false) Integer state,
            @RequestParam(required = false) Long gameId,
            @RequestParam(defaultValue = "{}") String order,
            @RequestParam(defaultValue = "0") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            Authentication authentication) {
        AuthUser user = getAuthUser(authentication);
        return tournamentService.userlist(state,gameId, order, page, size,user);
    }

    @PostMapping(value = "/round/log", name = "赛事列表信息")
    public Result roundLog(Long stageId) {
        return tournamentService.roundLog(stageId);
    }


    @ApiOperation(value = "非自由模式比赛结果添加", tags = {"赛事"}, notes = "非自由模式比赛结果添加")
    @PostMapping(value="/rank",name="非自由模式比赛结果添加")
    public Result rank(Long roundLogId,Integer aScore, Integer bScore ,Long win,String aImages ,String bImages ) {

            return roundLogService.rank(roundLogId,aScore,bScore,win,aImages,bImages);
    }

    @ApiOperation(value = "自由模式比赛结果添加", tags = {"赛事"}, notes = "自由模式比赛结果添加")
    @PostMapping(value="/free/rank",name="自由模式比赛结果添加")
    public Result freeRank(@RequestBody List<FreeRankVo> freeRankVos) {


        return tournamentTeamService.freeRank(freeRankVos);
    }

    @PostMapping(value = "/round/best", name = "round赛制修改")
    public Result roundBest(Round round) {
        roundService.update(round);
        return ResultGenerator.genSuccessResult();
    }

    /**
     * 只有单败双败涉及
     * @return
     */
    @PostMapping(value = "/round/log/swap", name = "对阵修改")
    public Result roundLogSwap(@RequestBody SwapRoundVo swapRoundVo) {
        return roundLogService.swap(swapRoundVo);
    }

    /**
     * 主持人收益列表
     */
    @PostMapping(value = "/organization/withdrawal/list", name = "主持人收益")
    public Result organization(
            @RequestParam(defaultValue = "0") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            Integer type,
            Integer status,
            String  organizationName,
            @RequestParam(defaultValue = "{}") String order,
            Authentication authentication){
        return  tournamentService.organization(type,status,organizationName,getAuthUser(authentication),page,size,order);
    }

    /**
     * 主持人申请提现
     */
    @PostMapping(value = "/organization/withdrawal/apply", name = "主持人申请提现")
    public Result withdrawalApply(@RequestParam Long tournamentId,
                                  @RequestParam String bankName,
                                  @RequestParam String userName,
                                  @RequestParam String bankAccount){
        return  tournamentService.withdrawalApply(tournamentId,bankName,userName,bankAccount);
    }

    /**
     * 通过或取消提现申请
     * @param status  3 成功 4 失败
     */
    @PostMapping(value = "/organization/withdrawal/agree", name = "主持人申请提现")
    public Result agree(@RequestParam Long tournamentId,
                      @RequestParam Integer status,
                      @RequestParam(required = false) String refuse,
                      @RequestParam(required = false) BigDecimal withdrawalProfit     ){
        return  tournamentService.agree(tournamentId,status,refuse,withdrawalProfit);
    }


    @PostMapping(value = "/reward/list", name = "礼品确认列表")
    public Result rewardList(Integer state,
                             String hostName,
                             @RequestParam(defaultValue = "0") Integer page,
                             @RequestParam(defaultValue = "10") Integer size,
                             @RequestParam(defaultValue = "{}") String order){
        return  tournamentService.rewardList(state,hostName,order,page,size);
    }

    @PostMapping(value = "/contestant", name = "参赛人员")
    public Result contestant(@RequestParam Long tournamentId){
        return  tournamentService.contestant(tournamentId);
    }


    @PostMapping(value = "/reward/grant", name = "参赛人员")
    public Result grant(Long rewardId, Long userId, Long tournamentId,Long id){
        TournamentRewardUser rewardUser = new TournamentRewardUser();
        rewardUser.setCreateTime(new Date().getTime());
        rewardUser.setId(id);
        rewardUser.setTournamentId(tournamentId);
        rewardUser.setUserId(userId);
        rewardUser.setRewardId(rewardId);
        Result result = tournamentService.rewardGrant(rewardUser);
        if(result.getCode() == 200){
            UserInfo info = userInfoService.findById(userId);
            TournamentReward reward = tournamentRewardService.findById(rewardId);
            EmailUtil.gmailSender(info.getEmail(),"Congratulations !! Your prizes of "+reward.getRewardName()+" has been successfully delivered into your Bountee account !!",null);
        }
        return  result;
    }


    @PostMapping(value = "/grant/confirm", name = "确认发放")
    public Result grantConfirm(Long rewardId, Boolean confirm ){
        return  tournamentService.grantConfirm(rewardId,confirm);
    }

    @PostMapping(value = "/top", name = "赛事置顶")
    public Result top(@RequestParam Long tournamentId,Boolean top){
        return  tournamentService.top(tournamentId,top);
    }

    @PostMapping(value = "/reset", name = "重新排序种子队伍")
    public Result reset(@RequestParam Long tournamentId){
        return  tournamentService.reset(tournamentId);
    }


    @PostMapping(value = "/update/team", name = "修改参赛队伍")
    public Result updateTeam(Long tournamentId,Long teamId,String userIds,Authentication authentication){
        String[] userId = new String[0];
        if(userIds!=null){
            userId  = userIds.split(",");
        }
        AuthUser user = getAuthUser(authentication);
       return   tournamentService.updateTeam(tournamentId,teamId,user,userId);
    }

}
